/**
 * Copyright 2014 @ z3q.net.
 * name :
 * author : jarryliu
 * date : 2013-12-12 16:52
 * description :
 * history :
 */

package seller

import (
    "dhfshop/models"
	"strings"
	"errors"
	"time"
	"github.com/astaxie/beego/orm"
)

//分销等级
type FenxiaoGrade struct {
	GradeId      int64       `orm:"column(grade_id);pk;auto" json:"grade_id" form:"grade_id"`  /* 编号 */
	CompanyId    int64         `orm:"column(company_id)" json:"company_id" form:"company_id"` //供应商ID
	Name         string      `orm:"column(name)" json:"name" form:"name"`        //等级名称
	Value        int         `orm:"column(value)" json:"value" form:"value"`     //等级值
	Number       int         `orm:"column(number)" json:"number" form:"number"`  //此等级分销商人数          
	//Discount     float32     `orm:"column(discount);digits(12);decimals(2)" json:"discount" form:"discount"` /* 折扣,暂时取消 */
	Amount       float32     `orm:"column(amount);digits(12);decimals(2)" json:"amount" form:"amount"` /* 交易金额 */
	Count        int         `orm:"column(count)" json:"count" form:"count"`                           /* 交易笔数 */
	CreatedAt    time.Time   `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"`  /* 创建时间 */
	CreatedAtStr string      `orm:"-" json:"created_at" form:"-"`
	UpdatedAt    time.Time   `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"` 
	UpdatedAtStr string      `orm:"-" json:"updated_at" form:"-"`
}

func init() {
    orm.RegisterModel(new(FenxiaoGrade))   
}

// 初始化默认等级
func InitDefaultGrades(companyId int64, levelSet []*FenxiaoGrade) error {
	if len(levelSet) != 0 {
		return errors.New("已经存在数据，无法初始化!")
	}
	var arr []*FenxiaoGrade = []*FenxiaoGrade{
		&FenxiaoGrade{
			CompanyId:  companyId,
			Name:       "普通会员",
			Value:      1,
			Number:     1,
			//Discount:   0.98,
			Amount:     0,	
			Count:      0,	
		},
		&FenxiaoGrade{
			CompanyId:  companyId,
			Name:       "铜牌会员",
			Value:      2,
			Number:      2,
			//Discount:   0.98,
			Amount:     100,
			Count:      100,
		},
		&FenxiaoGrade{
			CompanyId:  companyId,
			Name:       "银牌会员",
			Value:      3,
			Number:      3,
			//Discount:   0.98,
			Amount:     500,
			Count:      500,
		},
		&FenxiaoGrade{
			CompanyId:  companyId,
			Name:       "金牌会员",
			Value:      4,
			Number:      4,
			//Discount:   0.98,
			Amount:     1200,
			Count:      1200,
		},
		&FenxiaoGrade{
			CompanyId:  companyId,
			Name:       "白金会员",
			Value:      5,
			Number:      5,
			//Discount:   0.98,
			Amount:     1500,
			Count:      1500,
		},
	}

	for _, v := range arr {
		SaveFenxiaoGrade(companyId, v)
	}
	return nil
}


func AddFenxiaoGrade(m *FenxiaoGrade) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetFenxiaoGradeById(id int64) (v *FenxiaoGrade, err error) {
	o := models.GetDefaultDB()
	v = &FenxiaoGrade{GradeId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllFenxiaoGrades(query map[string]string, fields []string, order_by map[string]string, 
    offset int, limit int) ([]*FenxiaoGrade, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(FenxiaoGrade))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*FenxiaoGrade
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateFenxiaoGradeById(m *FenxiaoGrade, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := FenxiaoGrade{GradeId: m.GradeId}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}

func DeleteFenxiaoGrade(id int64) (err error) {
	o := models.GetDefaultDB()
	v := FenxiaoGrade{GradeId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

// 获取等级
func GetFenxiaoGradeByValue(partnerId, levelValue int) (member *FenxiaoGrade) {
	member = &FenxiaoGrade{}
	o := models.GetDefaultDB()
	o.QueryTable(new(FenxiaoGrade)).Filter("partner_id", partnerId).Filter("value", levelValue).One(member)
	return
}

// 获取下一个等级
func  GetNextFenxiaoGrade(partnerId, levelVal int) *FenxiaoGrade {
	var m *FenxiaoGrade
	o := models.GetDefaultDB()
	err := o.Raw("select * from member_level where partner_id=? AND value>? LIMIT 0,1", partnerId, levelVal).QueryRow(m)
	if err != nil {
		return nil
	}
	return m
}

// 获取会员等级
func GetFenxiaoGrades(partnerId int64) (pList []*FenxiaoGrade, err error) {
	o := models.GetDefaultDB()
	_, err = o.QueryTable(new(FenxiaoGrade)).Filter("partner_id", partnerId).All(&pList)
	return
}

// 保存等级
func SaveFenxiaoGrade(partnerId int64, v *FenxiaoGrade) (id int64, err error) {
	o := models.GetDefaultDB()
	m := FenxiaoGrade{GradeId: v.GradeId}
	if err = o.Read(&m); err == nil {
		if _, err = o.Update(v); err == nil {
		    id = int64(v.GradeId)
		}
	} else {
	    id, err = o.Insert(v)
	}
	return
}

/*
// 获取积分对应的等级
func  GetFenxiaoGradeByExp(partnerId int64, exp int) int {
	var levelId int
	this.Connector.ExecScalar(`SELECT lv.value FROM pt_member_level lv
	 	where lv.partner_id=? AND lv.require_exp <= ? AND lv.enabled=1
	 	 ORDER BY lv.require_exp DESC LIMIT 0,1`,
		&levelId, partnerId, exp)
	return levelId
}
*/
